import {
    getArticlesByBlocks,
    getClsArticlesByBlocks,
    searchArticlesBySecuName,
    searchArticlesByTokens
} from '@/server/controllers/articleController';
import { getSecuInfo, getTopRank } from '@/server/controllers/secuController';
import { format } from 'date-fns';
import Link from 'next/link';
import { fetchTopRank } from '@/lib/kpl';

const findKeys = (tokens, docText) => {
    if (!tokens) return '';
    const keys = tokens.filter((el) => docText.toLowerCase().includes(el.toLowerCase()));
    const keysStr = keys.join('；');
    return keysStr;
};

const ArticlesPage = async ({ params }) => {
    const { secuCode } = await params;
    const secuInfo = await getSecuInfo(secuCode);
    if (!secuInfo) return null;
    const ranks = await fetchTopRank(7);
    const tokens = secuInfo.tokens;
    const expect = secuInfo.expect || [];
    let vib_blocks = [];
    for (let i = 0; i < tokens.length; i++) {
        const token = tokens[i];
        for (let j = 0; j < ranks.length; j++) {
            const rank = ranks[j];
            if (token.includes(rank) || rank.includes(tokens[i])) {
                vib_blocks.push(rank);
            }
        }
    }
    vib_blocks = [...new Set(vib_blocks), ...expect, secuInfo.secu_name];
    vib_blocks = [...new Set(vib_blocks)];
    const articles = await getArticlesByBlocks(vib_blocks);
    const todayStr = format(new Date(), 'MM-dd');
    if (!articles) return null;
    // console.log(vib_blocks);
    return (
        <div className="w-full flex flex-col">
            {articles.map((item) => (
                <div
                    className="flex flex-col"
                    style={{
                        color: `${format(item.created_at, 'MM-dd HH:mm').includes(todayStr) ? 'cyan' : 'yellow'}`,
                        borderBottom: '1px solid #ccc',
                        fontSize: '0.4rem',
                        padding: 0,
                        margin: 0
                    }}
                    key={item.art_id}
                >
                    <p
                        className="flex flex-col w-full truncate"
                        style={{
                            color: `${item.art_url.includes('weixin.qq.com') ? 'red' : null}`
                        }}
                    >
                        <Link href={`${item.art_url}`} target="_blank" style={{ display: 'block', padding: 0, margin: 0 }}>
                            {format(item.created_at, 'MM-dd HH:mm')} | {item.art_title}
                        </Link>
                    </p>
                    <p>
                        <span style={{ color: 'yellow' }}>
                            {vib_blocks.filter((el) => item.art_title.includes(el)).join('；')}
                        </span>
                    </p>
                </div>
            ))}
        </div>
    );
};

export default ArticlesPage;
